package com.xinqi.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinqi.dto.PageData;
import com.xinqi.dto.Result;
import com.xinqi.entity.Blog;
import com.xinqi.entity.User;
import com.xinqi.mapper.BlogMapper;
import com.xinqi.service.BlogService;
import com.xinqi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements BlogService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public List<Blog> getPageByLimited(Page<Blog> pageParam) {
        Page<Blog> blogPage = baseMapper.selectPage(pageParam, null);
        List<Blog> records = blogPage.getRecords();
        return records;
    }

    @Override
    public Integer queryBlogLikesNumber(Long id) {
        String key = "BLOG_LIKED_KEY" + id;
        Set<String> set = stringRedisTemplate.opsForZSet().range(key, 0, -1);
        Integer likeNumber = 0;
        if (set != null) likeNumber = set.size();
        return likeNumber;
    }//这里的数据持久化就由定时任务去执行吧

    @Override
    public Result likeBlog(Long blogId, Long userId) {

        String key = "BLOG_LIKED_KEY" + blogId;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score == null) {
            //如果未点赞，可以点赞
            // 保存用户到Redis的set集合
            stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
        } else {
            //如果已点赞，取消点赞
            //把用户从Redis的set集合移除
            stringRedisTemplate.opsForZSet().remove(key, userId.toString());
        }
        return Result.ok();
    }

    //查询该博客下所有点赞的用户ids
    @Override
    public List<Long> queryAllBlogLikesUserIds(Long id) {
        String key = "BLOG_LIKED_KEY" + id;
        Set<String> stringUserList = stringRedisTemplate.opsForZSet().range(key, 0, -1);
        log.debug("stringUserList is {}",stringUserList);
        if (stringUserList == null || stringUserList.isEmpty()) return Collections.emptyList();

        List<Long> ids = stringUserList.stream().map(Long::valueOf).collect(Collectors.toList());

        return ids;
    }

    @Autowired
    private UserService userService;

    //查询该篇博客里所有点赞的用户users
    @Override
    public List<User> getAllBlogLikesUsersByBlogId(Long id) {
        List<Long> ids = queryAllBlogLikesUserIds(id);

        String idStr = StrUtil.join(",", ids);
        // 根据用户id查询用户 WHERE id IN ( 5 , 1 ) ORDER BY FIELD(id, 5, 1)
        List<User> users = new ArrayList<>(userService.query()
                .in("id", ids).last("ORDER BY FIELD(id," + idStr + ")")
                .list());
        return users;
    }

    @Override
    public void durableForLikeListByBogId(Long id){
        List<Long> ids = queryAllBlogLikesUserIds(id);
        String stringIds = ids.toString();

        String updateSql =  "like_list = " + "'" + stringIds + "' ," +
                            "like_number = " + ids.size();
        boolean isSuccess = update()
                .setSql(updateSql)
                .eq("id", id)
                .update();
    }
    @Resource
    private ThreadPoolExecutor dtpExecutor1;
    @Override
    public Result testDynamicTp() {
        dtpExecutor1.execute(() -> log.debug("{},test" , 48));
        return Result.ok();
    }
}
